﻿using daonaite.core.Attribute;
using daonaite.Model.system.menu;
using daonaite.Model.system.role;
using SqlSugar;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace daonaite.DAL.system
{
    /// <summary>
    /// 角色操作类
    /// </summary>
    [AutoLoad]
    public class D_role
    {
        private readonly ISqlSugarClient client;

        public D_role(ISqlSugarClient client)
        {
            this.client = client;
        }

        /// <summary>
        /// 分页查询角色
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<IEnumerable<sys_role>> selectpageAsync(Dto_role data, RefAsync<int> total)
        {
            var expable = Expressionable.Create<sys_role>();
            expable.And(it => it.deleteFlag == "N");
            expable.AndIF(data.id != null, it => it.id == data.id);
            expable.AndIF(!string.IsNullOrEmpty(data.roleName), it => it.roleName.Contains(data.roleName!));
            var exp = expable.ToExpression();
            return await client.Queryable<sys_role>().Where(exp).ToPageListAsync(data.pageIndex, data.pageSize, total);
        }

        /// <summary>
        /// 查询所有角色
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<sys_role>> selectall()
        {
            var expable = Expressionable.Create<sys_role>();
            expable.And(it => it.deleteFlag == "N");
            var exp = expable.ToExpression();
            return await client.Queryable<sys_role>().Where(exp).ToListAsync();
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> add(sys_role data)
        {
            return await client.Insertable(data).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        }

        /// <summary>
        /// 根据id获取角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<sys_role> getAsync(int id)
        {
            return await client.Queryable<sys_role>().FirstAsync(it => it.id == id);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> updateAsync(sys_role data)
        {
            return await client.Updateable(data).IgnoreColumns(ignoreAllNullColumns: true)
                   .WhereColumns(it => new { it.id }).ExecuteCommandAsync();
        }


        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> delete(int id)
        {
            return await client.Updateable<sys_role>().SetColumns(s => s.deleteFlag == "Y").Where(c => c.id == id).ExecuteCommandAsync();
        }
    }
}
